package cn.jee.controller;


import cn.jee.entity.User;
import cn.jee.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
  @Autowired
  private UserRepository userRepository;

//  @RequestMapping("/login")
//  public String login(@RequestParam String username, HttpSession session) {
//    User user = userRepository.findByUsername(username);
//    if (user == null) {
//      user = new User();
//      user.setUsername(username);
//      userRepository.save(user);
//    }
//    session.setAttribute("user", user);
//    return "redirect:/products";
//  }
@RequestMapping("/login")
public String login(@RequestParam String username, HttpSession session, Model model) {
  User user = userRepository.findByUsername(username);
  if (user == null) {
    user = new User();
    user.setUsername(username);
    userRepository.save(user);
  }
  session.setAttribute("user", user);
  model.addAttribute("user", user); // 添加用户到Model
  return "redirect:/products?username=" + username;
}
}
